package ex.util.generator;

import com.alibaba.fastjson.JSON;
import ex.datatypes.TaxiRide;
import ex.util.MyBatisUtils;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class GeneratorFromMysql implements SourceFunction<TaxiRide> {
    private volatile boolean running = true;

    @Override
    public void run(SourceContext<TaxiRide> ctx) throws Exception {
        //从数据库查询TaxiRide
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        String sqlId = "ex.springboot.mapper.TaxiRideMapper.selectTaxiRides";
        List<TaxiRide> dbTaxiRides = sqlSession.selectList(sqlId);

        System.out.println("dbTaxiRides size"+dbTaxiRides.size());
        while (running) {
            for (int i = 0; i < dbTaxiRides.size(); i++) {
                TaxiRide ride = dbTaxiRides.get(i);
                ctx.collect(ride);
                Thread.sleep(1000);
                if(i==dbTaxiRides.size()-1){
                    cancel();
                    sqlSession.close();
                }
            }
        }
    }

    @Override
    public void cancel() {
        running = false;
    }
}
